//获取权限方法
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};


layui.use(['layer', 'form', 'table', 'util', 'dtree','admin','laypage'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;
    var admin = layui.admin;
    var laypage = layui.laypage;

    var Authorization;//请求接口用
    var tableCatalog = {};//选中目录
    var reportType = [];//报告期类型

    var tableconfig={//表格参数
        current:1,
        meta_type:'',
        name:'',
        par_id:'',
        report_type:'',
        size:pageSize,

        count:0,
        fistRenderPage:true,//是否第一次渲染分页
    }
    var setting={//树设置
        catalogTreeSetting:{//原点区划树设置-区划变更弹窗使用
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandCatalogTree,
                onClick: zTreeCatalogOnClick,
                onNodeCreated: zTreeCatalogOnNodeCreated
            },
            view: {
                showIcon: true,
                showLine: true
            }
        }
    }

    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getTemplateIdenPower();
        getTemplateIdenManageTablePower();
        getIdentValuePower();

        getSelectReports();
        getTableClassifyList();
        lazyLoadCatalogTree();
    }

    // 打开新增目录弹窗
    $('#addTemplateIdenBtn').click(function () {
        showTemplateIdenModel();
    });
    // 打开编辑目录弹窗
    $('#editTemplateIdenBtn').click(function () {
        if(tableCatalog.hasOwnProperty("selectedCatalog")&&tableCatalog.selectedCatalog.id!="root"){
            showEditMenuModel(tableCatalog);
        }else if(tableCatalog.hasOwnProperty('selectedCatalog')&&tableCatalog.selectedCatalog.id=="root"){
            layer.msg('根目录不允许修改');
        }else{
            layer.msg('请先选中目录');
        }
    });
    //删除指标模板
    $('#deleteTemplateIdenBtn').click(function () {
        if(tableCatalog.hasOwnProperty("selectedCatalog")){
            showDeleteCatalogModel(tableCatalog);
        }else{
            layer.msg('请先选中目录');
        }
    });

    // 指标管理搜索按钮点击事件
    form.on('submit(formSubSearchTbLtrt)', function (data) {  
        tableconfig.name = data.field.keyword;
        queryTable();
    });
    //更多筛选点击
    $('#morefilter-btn-idenManage').click(function () {
        openMoreFilterModel();
        return false;
    })
    $(".layui-fluid .layui-card").click(function (node) {
        if(!(document.getElementById("idenMoreFilterModel").contains(node.target))){
            $("#idenMoreFilterModel").slideUp();
        }
    });
    //指标管理-更多筛选-搜索
    form.on('submit(modelSubmitUser)', function (data) {
        tableconfig.name = data.field.nickName;
        tableconfig.report_type = data.field.report_type;
        tableconfig.meta_type = data.field.meta_type;
        queryTable();
    });
    // 指标管理更多筛选
    form.on('submit(idenMoreFilterForm)', function (data) {
        $("#idenMoreFilterModel").slideUp();
        return false;
    });
    $("#closeIdenMoreFilterModel").click(function () {
        $("#idenMoreFilterModel").slideUp();
    });
    $('#add-btn-table').click(function () {
        if(tableCatalog.hasOwnProperty("selectedCatalog")&&tableCatalog.selectedCatalog.id!="root"){
            openAddTableModel();
        }else{
            layer.msg('请先选中目录子类');
        }
    });
    $('#import-btn-template-idenManage').click(function () {
        openImportIdenManage();
    })

    // 表格工具条点击事件
    table.on('tool(identGroupTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            showIndexClassEditModel(data);
        } else if (layEvent === 'delete') { // 删除
            showIndexClassDeleteModel(data);
        } else if(layEvent === 'templateManage'){//模板管理
            showTemplateManageModel(data);
        } else if(layEvent === 'importData'){//数据导入                 
            showImportDataModel(data);
        } else if(layEvent === 'queryData'){//数据查询
            showQueryDataModel(data);
        } else if(layEvent === 'setMenu'){//设置目录
            showSetCatalogModel(data);
        }
    });

    /*渲染数据表管理权限*/
    function getTemplateIdenPower() {
        var str = template("template-idenManage-tmpl",{});
        document.getElementById("template-idenManage-tmpl-box").innerHTML = str;
    }
    /*渲染数据表表格里的权限*/
    function getTemplateIdenManageTablePower() {
        var str = template("ident-template-idenManage-tmp",{});
        document.getElementById("ident-template-idenManage-box").innerHTML = str;
    }

    /*渲染指标模板权限*/
    function getIdentValuePower() {
        var str = template("template-iden-tmpl",{});
        document.getElementById("template-iden-tmpl-box").innerHTML = str;
    }

    //懒加载目录树
    function lazyLoadCatalogTree() {
        var req={
            parent_id : 'root',
        };
        axios.get(macroUrl.catalog.catalogTree,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var datas = response.data.data;
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.isParent = true;
                            row.sub = []; //存放子节点
                            row.drag = true;
                        }
                    }
                    var dataarr = [{"data_type":0,
                        "id":"root",
                        "name":"根目录",
                        "par_id":"",
                        "version":"0",
                        "sub":datas
                    }];
                    var treeObj = $.fn.zTree.init($("#catalogTree"), setting.catalogTreeSetting, dataarr);
                    var nodes = treeObj.getNodes();
                    if (nodes.length>0) {
                        treeObj.expandNode(nodes[0], true, false, true);
                    }

                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });

    }

    //展开树
    function onExpandCatalogTree(event, treeId, treeNode) {
        if(treeNode.sub.length==0){
            var req={
                parent_id : treeNode.id,
            };
            axios.get(macroUrl.catalog.catalogTree,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var datas = response.data.data;
                        if (datas.length > 0) {
                            for (const row of datas) {
                                row.isParent = true;
                                row.sub = []; //存放子节点
                                row.drag = true;
                            }
                        }
                        const treeObj = $.fn.zTree.getZTreeObj("catalogTree");
                        treeObj.addNodes(treeNode, datas);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

    }

    //树节点选中事件
    function zTreeCatalogOnClick(event, treeId, treeNode) {
        tableCatalog.selectedCatalog=treeNode;
        queryTable();
    }
    
    function zTreeCatalogOnNodeCreated(event, treeId, treeNode) {
        if(treeNode.tId == "catalogTree_2"){
            $("#catalogTree_2_a").click();
        }
    }
    //获取报告期类型
    function getSelectReports(){
        axios({
            method: 'get',
            url:metadataUrl.tableClassify.reportTableClassify,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data;
                    reportType = data.data;
                    var str = template("index_report_type-tmpl",data);
                    document.getElementById("index_report_type_box").innerHTML = str;//报告期不允许修改
                    form.render('select');
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    // 对象分类
    function getTableClassifyList() {
        var req={
            current: 1,
            size: 100
        };
        axios.get(metadataUrl.tableClassify.tableClassifyList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var str = template("index_meta_type_tmpl",data);
                    document.getElementById("index_meta_type_box").innerHTML = str;
                    form.render('select');
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    /*查询表格数据*/
    function queryTable() {
        var req={
            current:tableconfig.current,
            meta_type:tableconfig.meta_type,
            name:tableconfig.name,
            par_id:tableCatalog.selectedCatalog.id,
            report_type:tableconfig.report_type,
            size:pageSize
        };
        axios.get(macroUrl.table.queryTable,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){                    
                    var datas = response.data.data;
                    renderTable(datas)
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    /*渲染指标管理表格--搜索*/
    function renderTable(datas) {        
        table.render({
            elem: '#identGroupTable',
            size: 'sm', //小尺寸的表格
            data:datas.records,
            page: false,
            cellMinWidth: 100,
            cols: [[
                {type:'numbers', title: '#'},
                {field: 'name', align: 'center', title: '表名'},
                {field: 'catalogName', align: 'center', title: '表分类'},
                {field: 'reportType', align: 'center', title: '报告期类型',templet: function (d) {
                    let result = '';
                    for(let i in reportType){
                        if(d.reportType == reportType[i].value){
                            result = reportType[i].key;
                        }
                    }
                    return result;
                }},
                {field: 'startTime', align: 'center', title: '开始时间'},
                {field: 'endTime', align: 'center', title: '结束时间'},
                {field: 'localeOfSubmission', align: 'center', title: '地点'},
                {field: 'nickName', align: 'center', title: '多版本数据导入'},
                {align: 'center', toolbar: '#ident-template-idenManage-box', title: '操作', minWidth: 400}
            ]]
        });       
          
        //第一次才渲染分页
        if(tableconfig.fistRenderPage){        
            laypage.render({
                elem: 'page-box'
                ,count: datas.total,
                limit:pageSize,
                groups:1,
                current:tableconfig.current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){                    
                    if(!first){                         
                        tableconfig.current = obj.curr;
                        tableconfig.fistRenderPage = false;
                        queryTable();
                    }
                }
            });
        } 
    }

    /*显示新增指标模板弹窗*/
    function showTemplateIdenModel() {
        window.addIndexMenu = false;
        admin.open({
            title: '新增汇总对象目录',
            url: 'index/addIndexMenu.html',
            end: function () {
                if (window.addIndexMenu) {  // 判断表单操作成功标识，也可以使用top.xxx
                    lazyLoadCatalogTree();
                }
            },
            success: function (layero, dIndex) {
                window.tableCatalog = tableCatalog;
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }
    /*显示编辑对象目录弹窗*/
    function showEditMenuModel() {
        window.editIndexMenu = false;
        admin.open({
            title: '编辑汇总对象目录',
            url: 'index/editIndexMenu.html',
            end: function () {
                if (window.editIndexMenu) {  // 判断表单操作成功标识，也可以使用top.xxx
                    lazyLoadCatalogTree();
                }
            },
            success: function (layero, dIndex) {
                window.tableCatalog = tableCatalog;
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

    /*显示删除目录弹窗*/
    function showDeleteCatalogModel(obj) {
        layer.confirm('确定将永久删除目录“ '+obj.selectedCatalog.name+'”吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:macroUrl.catalog.deleteCatalog+obj.selectedCatalog.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("删除成功", {icon: 1});
                        lazyLoadCatalogTree();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    /*显示编辑指标管理弹窗*/
    function showIndexClassEditModel(data) {        
        window.editTableStatus = false;
        window.tableCatalog = tableCatalog;
        window.selectedTable = data;       
        admin.open({
            title: '编辑数据表',
            url: 'index/editIndexClass.html',
            area: ['400px', '700px'],
            end: function () {               
                if (window.editTableStatus) {  // 判断表单操作成功标识，也可以使用top.xxx                    
                    queryTable();
                }
            },
            success: function (layero, dIndex) {                
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'auto');
            }
        });

    }

    /*显示删除对象表弹窗*/
    function showIndexClassDeleteModel(obj) {
        layer.confirm('确认删除对象表：'+obj.name+'吗？', {
            skin: 'layui-layer-admin',
            size:'sm',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:macroUrl.table.deleteTable+obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("删除成功", {icon: 1});
                        tableconfig.fistRenderPage = true;
                        tableconfig.current = 1;
                        queryTable();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    /*显示更多筛选框*/
    function openMoreFilterModel() {
        $("#idenMoreFilterModel").slideDown();
    }
    /*显示新增数据表弹窗*/
    function openAddTableModel() {
        window.addTableStatus = false;
        admin.open({
            title: '新增数据表',
            url: 'index/addIndexClass.html',
            end: function () {
                if (window.addTableStatus) {  // 判断表单操作成功标识，也可以使用top.xxx   
                    //修改分页条的渲染设置                    
                    tableconfig.fistRenderPage = true;
                    tableconfig.current = 1;
                    queryTable();
                }
            },
            success: function (layero, dIndex) {
                window.tableCatalog = tableCatalog;                
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

    /*显示导入指标弹窗*/
    function openImportIdenManage() {
        layui.use(['admin','table'], function () {
            var $ = layui.jquery;
            var admin = layui.admin;
            var form = layui.form;
            var table = layui.table;

            admin.open({
                title: '导入指标',
                url: 'template/importIden.html',
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        })
    }

    /*显示设置目录弹窗*/
    function showSetCatalogModel(data) {
        window.selectedTable = data;
            admin.open({
                title: '设置目录',
                url: 'index/setCatalog.html',
                area:['1000px','700px'],
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
    }

    function showTemplateManageModel(data){
        var layIndex = admin.popupRight({
            type: 2,
            content: 'templateManage.html',
            offset: 'rt',
            area:['100vw;','calc(100vh - 30px)'],
            closeBtn: true,
            data: data,
            title: '模板管理',
            id:'templateModelPage',
            end: function () {
                if (admin.getLayerData(layIndex, 'formOk')) {  // 判断表单操作成功标识
                     // 成功刷新表格
                }
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

    function showImportDataModel(data){
        admin.popupRight({
            type: 2,
            title: '数据导入',
            content: 'importData.html',
            offset: 'rt',
            area:['100vw;','calc(100vh - 30px)'],
            closeBtn: true,
            data: data,            
            end: function () {
               
            },
            success: function (layero, dIndex) {                
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

    function showQueryDataModel(data){
        admin.popupRight({
            type: 2,
            title: '数据查询',
            content: 'queryData.html',
            offset: 'rt',
            area:['100vw;','calc(100vh - 30px)'],
            closeBtn: true,
            data: data,
            end: function () {

            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }
});


